﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using WPFCommon.FileManipulation;
using WPFCommon.Interface;

namespace WPFCommon.Logger
{
    /// <summary>
    /// Log decimal numbers to a file
    /// Warning:
    /// Make sure IO time for appending to file is less than time of data overflowing
    /// </summary>
    public class DataLogger : IDataLogger, IFlushAll
    {

        #region private fields

        private readonly List<double> _dataBuffer = new List<double>();

        private string _filePath;



        #endregion

        #region ctor    

        public DataLogger(string filePath)
        {
            _filePath = filePath;
        }

        #endregion
        
        #region prop

        /// <summary>
        /// When count of data in buffer reaches BufferSize,
        /// the buffer will be appended to file
        /// </summary>
        public int BufferSize { get; set; } = 1000;

        #endregion

        public void Log(double data)
        {
            lock (_dataBuffer)
            {
                if (_dataBuffer.Count >= BufferSize)
                {
                    var copy = _dataBuffer.ToArray();
                    _dataBuffer.Clear();
                    // Potential bugs
                    Task.Run(() => { AppendDataToFile(copy);});
                }
                
                _dataBuffer.Add(data);
            }
        }

        private void AppendDataToFile(double[] copy)
        {
            var content = string.Join(Environment.NewLine, copy);
            if(File.Exists(_filePath))
            {
                FileHelper.CreateEmptyFileAndContainingFolder(_filePath);
            }
            File.AppendAllText(_filePath, content + Environment.NewLine);
        }

        public void FlushAll()
        {
            lock (_dataBuffer)
            {
                AppendDataToFile(_dataBuffer.ToArray());
            }
        }
    }
}